package com.assets.Scrap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.core.widget.NestedScrollView;

import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.Repairs.CmlRequestBody;
import com.assets.Repairs.GridViewAdapter;
import com.assets.Repairs.MainConstant;
import com.assets.Repairs.PictureSelectorConfig;
import com.assets.Repairs.PlusImageActivity;
import com.assets.db.DatabaseHelper;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/5/11.
 */

public class Scrap_Data extends Activity implements OnDismissListener {
    private String repairsId, number, states;//单号,编号
    private Context mContext;
    private ImageView fh;
    public static final int RECORD_SYSTEM_VIDEO = 1;
    private Button uploading;
    ProgressDialog pd;
    File mediaFile;
    File mediaStorageDir;
    Uri fileUri;
    private VideoView mVideoView;
    private ImageView add_video;
    private String url = "http://" + Url.IP + "/api/scrapSubmit";
    private NestedScrollView scroll;
    private EditText remark;
    private TextView Section, Asset_name, Model, title_text;//部门，名称，型号，备注
    private GridView gridView;
    private ArrayList<String> mPicList = new ArrayList<>(); //上传的图片凭证的数据源
    private GridViewAdapter mGridViewAddImgAdapter; //展示上传的图片的适配器
    private DatabaseHelper mydata;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scrap_data);

        mydata = new DatabaseHelper(this, "mydata.db", null, 1);
        mContext = this;

        inview();
        gridView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    scroll.requestDisallowInterceptTouchEvent(false);
                } else {
                    scroll.requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });
        add_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reconverIntent(add_video);
            }
        });
        uploading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // if (mPicList.size()>0){
                new AlertView(" 提示！", "是否上传", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position == 0) {
                            pd = new ProgressDialog(mContext);
                            pd.setMessage("上传数据中...");//设置消息
                            pd.setMax(100);//设置进度条的最大值
                            pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                            ;
                            pd.setCancelable(true);//这是是否可撤销/也就是这个对话框是否可以关闭
                            pd.setIndeterminate(false);//设置是否是确定值
                            pd.show();//展示对话框
                            upload();
                        }
                        if (position == -1) {

                        }

                    }
                }).setCancelable(true).setOnDismissListener(Scrap_Data.this).show();

                //}else Toast.makeText(Scrap_Data.this,"请添加图片",Toast.LENGTH_SHORT).show();

            }
        });
    }

    private void upload() {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        int i = 0;
        for (String path : mPicList) {
            builder.addFormDataPart(i + "upload", i + number + ".png", RequestBody.create(MediaType.parse(i + number + "/png"), new File(path)));
            i++;
        }
        if (mediaFile != null) {
            builder.addFormDataPart("video", "ing.mp4",
                    RequestBody.create(MediaType.parse("ing/mp4"), mediaFile));
        }
        builder.addFormDataPart("assetNumber", number)
                .addFormDataPart("scrapId", repairsId);
        Request.Builder request = new Request
                .Builder()
                .url(url)
                .post(new CmlRequestBody(builder.build()) {
                    @Override
                    public void loading(long current, long total, boolean done) {
                        Log.i("", "current:" + current + ";total:" + total);
                        if (!done) {
                            sendMessage(3, current, total, "");
                        }
                    }
                });
        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build().newBuilder()
                .connectTimeout(5000, TimeUnit.SECONDS) //连接超时
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))//http
                .build();
        okHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // Log.i("zzzzzzzzzzzzz",e.toString()+call.toString());
                sendMessage(1, 0, 0, call.toString());
            }

            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful() || response == null || response.body() == null) {
                    //  Log.i("zzzzzzz",response.toString()+call.toString());
                    sendMessage(1, 0, 0, "");
                } else {
                    //返回值处理
                    sendMessage(2, 0, 0, "");
                }
            }
        });
    }

    public void reconverIntent(View view) {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), System.currentTimeMillis() + ".mp4");
            fileUri = FileProvider.getUriForFile(this, "com.shanXiAssets.provider", file);
            mediaFile = file;
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), System.currentTimeMillis() + ".mp4");
            fileUri = Uri.fromFile(file);
            mediaFile = file;
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);     //限制的录制时长 以秒为单位
        //  intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 10 * 1024 * 1024L);        //限制视频文件大小 以字节为单位
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);      //设置拍摄的质量0~1
        //   intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, false);        // 全屏设置
        startActivityForResult(intent, RECORD_SYSTEM_VIDEO);

    }

    private void inview() {
        add_video = (ImageView) findViewById(R.id.add_mv);
        mVideoView = (VideoView) findViewById(R.id.videoView);
        uploading = (Button) findViewById(R.id.uploading);
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("资产详情");
        fh = (ImageView) findViewById(R.id.fh);
        scroll = (NestedScrollView) findViewById(R.id.scroll);
        gridView = (GridView) findViewById(R.id.gridView);
        remark = (EditText) findViewById(R.id.remark);
        Section = (TextView) findViewById(R.id.maintenance);
        Asset_name = (TextView) findViewById(R.id.name);
        Model = (TextView) findViewById(R.id.model);
        Intent intent = getIntent();
        repairsId = intent.getStringExtra("repairsId");
        number = intent.getStringExtra("number");
        remark.setText(intent.getStringExtra("remark"));
        Section.setText(intent.getStringExtra("Section"));
        Asset_name.setText(intent.getStringExtra("Asset_name"));
        Model.setText(intent.getStringExtra("Model"));
        initGridView();
        fh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    //初始化展示上传图片的GridView
    private void initGridView() {
        mGridViewAddImgAdapter = new GridViewAdapter(mContext, mPicList);
        gridView.setAdapter(mGridViewAddImgAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if (position == mPicList.size()) {
                    //如果“增加按钮形状的”图片的位置是最后一张，且添加了的图片的数量不超过5张，才能点击
                    if (mPicList.size() == 5) {
                        //最多添加5张图片
                        viewPluImg(position);
                    } else {
                        //添加凭证图片
                        selectPic(5 - mPicList.size());
                    }
                } else {
                    viewPluImg(position);
                }
            }
        });
    }

    //查看大图
    private void viewPluImg(int position) {
        Intent intent = new Intent(mContext, PlusImageActivity.class);
        intent.putStringArrayListExtra(MainConstant.IMG_LIST, mPicList);
        intent.putExtra(MainConstant.POSITION, position);
        startActivityForResult(intent, MainConstant.REQUEST_CODE_MAIN);
    }

    /**
     * 打开相册或者照相机选择凭证图片，最多5张
     *
     * @param maxTotal 最多选择的图片的数量
     */
    private void selectPic(int maxTotal) {
        PictureSelectorConfig.initMultiConfig(this, maxTotal);
    }

    // 处理选择的照片的地址
    private void refreshAdapter(List<LocalMedia> picList) {
        for (LocalMedia localMedia : picList) {
            //被压缩后的图片路径
            if (localMedia.isCompressed()) {
                String compressPath = localMedia.getCompressPath(); //压缩后的图片路径
                mPicList.add(compressPath); //把图片添加到将要上传的图片数组中
                mGridViewAddImgAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    refreshAdapter(PictureSelector.obtainMultipleResult(data));
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    break;
                case RECORD_SYSTEM_VIDEO:
                    mVideoView.setVideoURI(data.getData());
                    mVideoView.start();
                    break;
            }
        }

        if (requestCode == MainConstant.REQUEST_CODE_MAIN && resultCode == MainConstant.RESULT_CODE_VIEW_IMG) {
            //查看大图页面删除了图片
            ArrayList<String> toDeletePicList = data.getStringArrayListExtra(MainConstant.IMG_LIST); //要删除的图片的集合
            mPicList.clear();
            mPicList.addAll(toDeletePicList);
            mGridViewAddImgAdapter.notifyDataSetChanged();
        }
    }

    public void sendMessage(int what, long current, long total, String msg) {
        Message message = Message.obtain();
        message.what = what;
        message.arg1 = (int) current;
        message.arg2 = (int) total;
        message.obj = msg;
        handler.sendMessage(message);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    //上传失败
                    pd.dismiss();
                    Toast.makeText(mContext, "上传失败", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    pd.dismiss();
                    finish();
                    Toast.makeText(mContext, "上传成功", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    //上传进度
                    int current = msg.arg1;
                    int total = msg.arg2;
                    Log.i("wwwwwwww", current + "");
                    pd.setProgress(current);
                    break;
            }
        }
    };

    @Override
    public void onDismiss(Object o) {

    }

    /**
     * Create a File for saving an video
     */
    private File getOutputMediaFile() {
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            Toast.makeText(this, "请检查SDCard！", Toast.LENGTH_SHORT).show();
            return null;
        }

        mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "MyCameraApp");
        if (!mediaStorageDir.exists()) {
            mediaStorageDir.mkdirs();
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
        return mediaFile;
    }

}
